package com.hgk.common.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

public class GetFileSizeUtil {

	private static GetFileSizeUtil instance;

	public GetFileSizeUtil() {

	}

	public static GetFileSizeUtil getInstance() {
		if (instance == null) {
			instance = new GetFileSizeUtil();
		}
		return instance;
	}

	public long getFileSizes(File f) throws Exception {
		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			f.createNewFile();
		}
		return s;
	}

	public String FormetFileSize(long fileS) {// 转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
        fileS=fileS/2;
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		if(fileSizeString.equalsIgnoreCase(".00b")){
			fileSizeString="0.0KB";
		}
		return fileSizeString;
	}

	/** 
    * 获取文件夹大小 
    * @param file File实例 
    * @return long 单位为M 
    * @throws Exception 
    */  
   public long getFolderSize(File file)throws Exception{
       long size = 0;
       File[] fileList = file.listFiles();
       for (int i = 0; i < fileList.length; i++)  
       {  
           if (fileList[i].isDirectory())  
           {  
               size = size + getFolderSize(fileList[i]);  
           } else  
           {  
               size = size + fileList[i].length();  
           }  
       }  
//       return size/1048576;  
       return size;
   }  
}